<?php

namespace app\wechat\service;

use app\wechat\model\MiniSendMessageRecordModel;
use app\wechat\model\MiniSubscribeMessageModel;

/**
 * 订阅消息
 *
 * @Author tanruizheng
 * @DateTime 2021-08-17
 */
class SubscribeMessageService extends MiniService
{
    /**
     * 发送订阅消息
     *
     * @Author tanruizheng
     * @DateTime 2021-08-24
     * @param [type] $templateId
     * @param [type] $touser
     * @param array $data
     * @param string $page
     * @return void
     */
    public function subscribeMessageSend($templateId, $touser, $data = [], $page = ''){
        try {
            $data = [
                'template_id'   => $templateId, // 所需下发的订阅模板id
                'touser'        => $touser,     // 接收者（用户）的 openid
                'page'          => '',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
                'data'          => $data,
            ];
            
            $res = $this->getApp()->subscribe_message->send($data);
            if($res['errcode'] == 0){
                $response = self::createSuccess('发送成功');
                $result = '发送成功';
            }else{
                $response = self::createFail($res['errmsg']);
                $result = '发送失败';
            }
        } catch (\Exception $e) {
            $response = self::createFail($e->getMessage());
            $result = '发送失败';
        }
        $MiniSendMessageRecordModel = new MiniSendMessageRecordModel();
        $MiniSendMessageRecordModel->app_id = $this->appId;
        $MiniSendMessageRecordModel->open_id = $touser;
        $MiniSendMessageRecordModel->template_id = $templateId;
        $MiniSendMessageRecordModel->page = $page;
        $MiniSendMessageRecordModel->data = json_encode($data);
        $MiniSendMessageRecordModel->result = $result;
        $MiniSendMessageRecordModel->send_time = time();
        $MiniSendMessageRecordModel->save();
        return $response;
    }

    /**
     * 获取当前帐号下的个人模板列表
     *
     * @Author tanruizheng
     * @DateTime 2021-08-24
     * @return void
     */
    public function getTemplates(){
        try {
            $res = $this->getApp()->subscribe_message->getTemplates();
            if($res['errcode'] == 0){
                return self::createSuccess('获取成功',$res['data'] ?? []);
            }else{
                return self::createFail($res['errmsg']);
            }
        } catch (\Exception $e) {
            return self::createFail($e->getMessage());
        }
    }

    /**
     * 同步订阅消息
     *
     * @Author tanruizheng
     * @DateTime 2021-08-25
     * @return void
     */
    public function syncTemplates(){
        $res = $this->getTemplates();
        if($res['status']){
            $templateList = $res['data'];
            foreach ($templateList as $item) {
                $temlateId = $item['priTmplId'];//模板ID
                $MiniSubscribeMessage = MiniSubscribeMessageModel::where('template_id', $temlateId)->findOrEmpty();
                $MiniSubscribeMessage->app_id = $this->appId;
                $MiniSubscribeMessage->template_id = $temlateId;
                $MiniSubscribeMessage->title = $item['title'];
                $MiniSubscribeMessage->content = $item['content'];
                $MiniSubscribeMessage->example = $item['example'];
                $MiniSubscribeMessage->type = $item['type'];
                $MiniSubscribeMessage->save();
            }
            return self::createSuccess('同步成功');
        }else{
            return self::createFail('同步失败');
        }
    }
}